package com.zmn.oms.manager.utils;//package com.zmn.manager.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
* @author nowind
* @date 16/1/11 23:35
*/
public class SpringBeanFactoryUtil implements ApplicationContextAware {

   /**
    * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
    * 在非controller类中获取方式：ApplicationContext context = SpringBeanFactoryUtil.getApplicationContext();
    * applicationContext.xml中配置：<bean id="applicationContext" class="com.zmn.common.utils.spring.SpringBeanFactoryUtil"/>
    */
   private static ApplicationContext applicationContext = null;


   /**
    * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量
    */
   @Override
   public void setApplicationContext(ApplicationContext context) throws BeansException {
       applicationContext = context;
   }
   /**
    * 取得存储在静态变量中的ApplicationContext.
    */
   public static ApplicationContext getApplicationContext() {
       checkApplicationContext();
       return applicationContext;
   }

   public static Object getServiceBean(String service) {
       checkApplicationContext();
       return applicationContext.getBean(service);
   }

   /**
    * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
    */
   @SuppressWarnings("unchecked")
   public static <T> T getBean(Class<T> clazz) {
       checkApplicationContext();
       return (T) applicationContext.getBean(clazz.getSimpleName());
   }

   /**
    * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型
    */
   @SuppressWarnings("unchecked")
   public static <T> T getBean(String clazz) {
       checkApplicationContext();
       return (T) applicationContext.getBean(clazz);
   }

   @SuppressWarnings("unchecked")
   public static <T> T getServiceBean(Class<T> clazz) {
       checkApplicationContext();
       return (T) applicationContext.getBean(clazz.getSimpleName());
   }


   /**
    * 清除applicationContext静态变量.
    */
   public static void cleanApplicationContext() {
       applicationContext = null;
   }

   private static void checkApplicationContext() {
       if (applicationContext == null) {
           throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
       }
   }


}
